This project will assure you have mastered the subjects covered in the statistics lessons. The hope is to have this project be as comprehensive of these topics as possible. Good luck!
A/B tests are very commonly performed by data analysts and data scientists. It is important that you get some practice working with the difficulties of these
For this project, you will be working to understand the results of an A/B test run by an e-commerce website. Your goal is to work through this notebook to help the company understand if they should implement the new page, keep the old page, or perhaps run the experiment longer to make their decision.
As you work through this notebook, follow along in the classroom and answer the corresponding quiz questions associated with each question. The labels for each classroom concept are provided for each question. This will assure you are on the right track as you work through the project, and you can feel more confident in your final submission meeting the criteria. As a final check, assure you meet all the criteria on the RUBRIC.
To get started, let's import our libraries.
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
%matplotlib inline
#We are setting the seed to assure you get the same answers on quizzes as we set up
random.seed(42)
1.
Now, read in the ab_data.csv
data. Store it in df
. Use your dataframe to answer the questions in Quiz 1 of the classroom.
a. Read in the dataset and take a look at the top few rows here:
df = pd.read_csv('ab_data.csv')
df.head()
b. Use the below cell to find the number of rows in the dataset.
df.shape
df.shape[0]
len(df)
c. The number of unique users in the dataset.
df.user_id.unique()
df.user_id.nunique()
df.describe()
total_users = len(df.user_id.value_counts())
print(total_users)
df.user_id.nunique()
d. The proportion of users converted.
df.converted.mean()
df[((df['group'] == 'treatment') == (df['landing_page'] == 'new_page')) == False].shape[0]
f. Do any of the rows have missing values?
df.info()
sum(df.isnull().sum())
2.
For the rows where treatment is not aligned with new_page or control is not aligned with old_page, we cannot be sure if this row truly received the new or old page. Use Quiz 2 in the classroom to provide how we should handle these rows.
a. Now use the answer to the quiz to create a new dataset that meets the specifications from the quiz. Store your new dataframe in df2.
df2 = df.drop(df[(df['group'] == 'treatment') & (df['landing_page'] == 'old_page')].index)
df2 = df2.drop(df2[(df2['group'] == 'control') & (df2['landing_page'] == 'new_page')].index)
df2.shape
df2.head()
df2.count()
# Checking all of the correct rows were removed - The result must be 0
df2[((df2.group == 'treatment') == (df2.landing_page == 'new_page')) == False].shape[0]
df2.head()
3.
Use df2 and the cells below to answer questions for Quiz3 in the classroom.
a. How many unique user_ids are in df2?
# Finding the number of unique users
df2.user_id.nunique()
b. There is one user_id repeated in df2. What is it?
# Finding the duplicate id
df2[df2.duplicated('user_id')]
c. What is the row information for the repeat user_id?
df2[df2.duplicated(subset=['user_id'], keep='first')]
d. Remove one of the rows with a duplicate user_id, but keep your dataframe as df2.
df2 = df2.drop_duplicates(subset=['user_id'], keep='first')
4.
Use df2 in the below cells to answer the quiz questions related to Quiz 4 in the classroom.
a. What is the probability of an individual converting regardless of the page they receive?
df2.converted.mean()
df2['converted'][df2['converted'] == 1].sum() / len(df2)
b. Given that an individual was in the control
group, what is the probability they converted?
df2.query('group == "control"').converted.mean()
c. Given that an individual was in the treatment
group, what is the probability they converted?
df2.query('group == "treatment"').converted.mean()
d. What is the probability that an individual received the new page?
len(df2.query('landing_page == "new_page"')) / len(df2)
### There are several ways to find that probability such as;
df2.query("landing_page == 'new_page'").shape[0] / df2.landing_page.shape[0]
e. Consider your results from a. through d. above, and explain below whether you think there is sufficient evidence to say that the new treatment page leads to more conversions.
Notice that because of the time stamp associated with each event, you could technically run a hypothesis test continuously as each observation was observed.
However, then the hard question is do you stop as soon as one page is considered significantly better than another or does it need to happen consistently for a certain amount of time? How long do you run to render a decision that neither page is better than another?
These questions are the difficult parts associated with A/B tests in general.
1.
For now, consider you need to make the decision just based on all the data provided. If you want to assume that the old page is better unless the new page proves to be definitely better at a Type I error rate of 5%, what should your null and alternative hypotheses be? You can state your hypothesis in terms of words or in terms of $p_{old}$ and $p_{new}$, which are the converted rates for the old and new pages.
In the previous section, we calculated the p-value, which is the probability of obtaining our statistic or a more extreme value if zero is true. Having a high p-value means that the statistic is more likely to come from our null hypothesis, so there is no statistical evidence to reject the null hypothesis that the old pages are the same or slightly better than the new ones
2.
Assume under the null hypothesis, $p_{new}$ and $p_{old}$ both have "true" success rates equal to the converted success rate regardless of page - that is $p_{new}$ and $p_{old}$ are equal. Furthermore, assume they are equal to the converted rate in ab_data.csv regardless of the page.
Use a sample size for each page equal to the ones in ab_data.csv.
Perform the sampling distribution for the difference in converted between the two pages over 10,000 iterations of calculating an estimate from the null.
Use the cells below to provide the necessary parts of this simulation. If this doesn't make complete sense right now, don't worry - you are going to work through the problems below to complete this problem. You can use Quiz 5 in the classroom to make sure you are on the right track.
a. What is the convert rate for $p_{new}$ under the null?
#p_new = df2.converted.mean()
p_new = df2.query('landing_page == "new_page"').converted.mean()
p_new
b. What is the convert rate for $p_{old}$ under the null?
#p_old = df2.converted.mean()
p_old = df2.query('landing_page == "old_page"').converted.mean()
p_old
p_new - p_old
c. What is $n_{new}$?
n_new = df2['group'][df2['group'] == 'treatment'].count()
n_new
d. What is $n_{old}$?
n_old = len(df2.query('landing_page == "old_page"'))
n_old
e. Simulate $n_{new}$ transactions with a convert rate of $p_{new}$ under the null. Store these $n_{new}$ 1's and 0's in new_page_converted.
new_page_converted = np.random.choice(2, size=n_new ,p=[p_new,1 - p_new])
new_page_converted.mean()
f. Simulate $n_{old}$ transactions with a convert rate of $p_{old}$ under the null. Store these $n_{old}$ 1's and 0's in old_page_converted.
old_page_converted = np.random.choice(2, size=n_old ,p=[p_old,1 - p_old])
old_page_converted.mean()
g. Find $p_{new}$ - $p_{old}$ for your simulated values from part (e) and (f).
new_page_converted = new_page_converted[:145274]
new_page_converted.mean() - old_page_converted.mean()
h. Simulate 10,000 $p_{new}$ - $p_{old}$ values using this same process similarly to the one you calculated in parts a. through g. above. Store all 10,000 values in a numpy array called p_diffs.
#Simulate 10000 samples of the differences in conversion rates
p_diffs = []
for _ in range(10000):
new_page_converted = np.random.binomial(1, p_new, n_new)
old_page_converted = np.random.binomial(1, p_old, n_old)
new_page_p = new_page_converted.mean()
old_page_p = old_page_converted.mean()
p_diffs.append(new_page_p - old_page_p)
i. Plot a histogram of the p_diffs. Does this plot look like what you expected? Use the matching problem in the classroom to assure you fully understand what was computed here.
#Show the histogram
plt.hist(p_diffs);
lower, upper = np.percentile(p_diffs, 2.5), np.percentile(p_diffs, 97.5)
plt.axvline(x=lower, color = "red");
plt.axvline(x=upper, color = "red");
plt.ylabel('Frequency', fontsize = 18);
plt.xlabel('Difference in Menas', fontsize = 18);
plt.title('P_Diff Plot', fontsize = 18);
j. What proportion of the p_diffs are greater than the actual difference observed in ab_data.csv?
actual_diff = df2.query('landing_page == "new_page"').converted.mean() - df2.query('landing_page == "old_page"').converted.mean()
p_diffs = np.array(p_diffs)
null_vals = np.random.normal(0, p_diffs.std(), p_diffs.size)
# plot null distribution
plt.hist(null_vals);
# plot line for observed statistic
plt.axvline(actual_diff, color = "red");
plt.ylabel('Frequency', fontsize = 18);
plt.xlabel('Difference in Menas', fontsize = 18);
plt.title('Null Values Plot & Means Actual Diff', fontsize = 18);
#difference of converted rates
actual_diff = (df2[df2['group'] == "treatment"]['converted'].mean()) - (df2[df2['group'] == "control"]['converted'].mean())
actual_diff
#Convert to numpy array and calculate the p-value
(null_vals > actual_diff).mean()
k. In words, explain what you just computed in part j. What is this value called in scientific studies? What does this value mean in terms of whether or not there is a difference between the new and old pages?
l. We could also use a built-in to achieve similar results. Though using the built-in might be easier to code, the above portions are a walkthrough of the ideas that are critical to correctly thinking about statistical significance. Fill in the below to calculate the number of conversions for each page, as well as the number of individuals who received each page. Let n_old
and n_new
refer the the number of rows associated with the old page and new pages, respectively.
import statsmodels.api as sm
#Number of conversions for each page
convert_old = df2.query('group == "control"').converted.sum()
convert_new = df2.query('group == "treatment"').converted.sum()
#Number of individuals who received each page
n_old = df2.query("landing_page == 'old_page'").shape[0]
n_new = df2.query("landing_page == 'new_page'").shape[0]
convert_old, convert_new, n_old, n_new
m. Now use stats.proportions_ztest
to compute your test statistic and p-value. Here is a helpful link on using the built in.
z_score, p_value = sm.stats.proportions_ztest([convert_old, convert_new], [n_old, n_new], alternative='smaller')
z_score, p_value
n. What do the z-score and p-value you computed in the previous question mean for the conversion rates of the old and new pages? Do they agree with the findings in parts j. and k.?
from scipy.stats import norm
# how significant our z-score is
print(norm.cdf(z_score))
# for our single-sides test, assumed at 95% confidence level, we calculate:
print(norm.ppf(1-(0.05/2)))
1.
In this final part, you will see that the result you acheived in the previous A/B test can also be acheived by performing regression.
a. Since each row is either a conversion or no conversion, what type of regression should you be performing in this case?
b. The goal is to use statsmodels to fit the regression model you specified in part a. to see if there is a significant difference in conversion based on which page a customer receives. However, you first need to create a column for the intercept, and create a dummy variable column for which page each user received. Add an intercept column, as well as an ab_page column, which is 1 when an individual receives the treatment and 0 if control.
df2['intercept'] = 1
df2['ab_page'] = pd.get_dummies(df2['group'])['treatment']
df2.head(3)
c. Use statsmodels to import your regression model. Instantiate the model, and fit the model using the two columns you created in part b. to predict whether or not an individual converts.
df2['intercept'] = 1
mod = sm.Logit(df2.converted, df2[['intercept', 'ab_page']])
results = mod.fit()
results.summary()
print(np.exp(res.params))
d. Provide the summary of your model below, and use it as necessary to answer the following questions.
e. What is the p-value associated with ab_page? Why does it differ from the value you found in Part II?
Hint: What are the null and alternative hypotheses associated with your regression model, and how do they compare to the null and alternative hypotheses in the Part II?
The result of the logit regression model, our intercept is 0.002 and the slope is -0.015. When using logit regression models, the focus is on the probability and likelihood of success. Running [np.exp(res.params)] will give us the coverage probability which is (0.98). The chances of conversion are therefore very close to 1, which means that the probability of having someone to convert is almost equal to the probability of not having someone to convert on the new_page. This confirms our null hypothesis and there is no evidence that the new_page is better. The p-value (0.1899) calculated by the logistic regression is the same as that calculated by the z-test function. Again, these two p-values are different from the one calculated in j and k parts, because we considered from the start that p_old and p_new are equal, which is not the case in the z-test and the logistic regression model. The p-value (0.1899) is high, confirming the failure to reject the null hypothesis.
f. Now, you are considering other things that might influence whether or not an individual converts. Discuss why it is a good idea to consider other factors to add into your regression model. Are there any disadvantages to adding additional terms into your regression model?
Before drawing a good conclusion, we first need to see all the parameters, because several things can influence the conversion rate. We have to take into account the number of people who participated, was the duration of the test sufficient, in what period of time was the test organised? If the test was organised at the beginning of the week or at the weekend for example, this can influence the result of the test. The environment in which people live can also be important.
g. Now along with testing if the conversion rate changes for different pages, also add an effect based on which country a user lives. You will need to read in the countries.csv dataset and merge together your datasets on the approporiate rows. Here are the docs for joining tables.
Does it appear that country had an impact on conversion? Don't forget to create dummy variables for these country columns - Hint: You will need two columns for the three dummy variables. Provide the statistical output as well as a written response to answer this question.
My answer to the question
I think countries have no impact on conversion. If you check the conversion rate for the 3 countries CA, UK and US, the result is almost the same.
The conversion ratio per country is less than
TURNOVER: 0.115318
UNITED KINGDOM: 0.120594
UNITED STATES: 0.119547
We need to dig deeper and provide more statistical answers to this question by integrating our data into a model and checking probabilities
countries_df = pd.read_csv('./countries.csv')
df_new = countries_df.set_index('user_id').join(df2.set_index('user_id'), how='inner')
### Checking the head(3)
df_new.head()
countries_df.groupby('country').count()
df_new.country.unique()
### Create the necessary dummy variables
df_new[['CA', 'US', 'UK']] = pd.get_dummies(df_new['country'])[['CA','US', 'UK']]
df_new.head()
log_mod = sm.Logit(df_new['converted'], df_new[['intercept', 'UK', 'US']])
results = log_mod.fit()
results.summary()
df_new.query('country == "US"').converted.mean(),df_new.query('country == "UK"').converted.mean(),df_new.query('country == "CA"').converted.mean()
df_new.groupby('country').mean()
h. Though you have now looked at the individual factors of country and page on conversion, we would now like to look at an interaction between page and country to see if there significant effects on conversion. Create the necessary additional columns, and fit the new model.
Provide the summary results, and your conclusions based on the results.
### Fit Your Linear Model And Obtain the Results
df_new['intercept'] = 1
log_mod = sm.Logit(df_new['converted'], df_new[['CA', 'US', 'intercept', 'ab_page']])
results = log_mod.fit()
results.summary()
df_new['US_ab_page'] = df_new['US'] * df_new['ab_page']
df_new['CA_ab_page'] = df_new['CA'] * df_new['ab_page']
df_new.info()
sum(df.isnull().sum())
df_new.country.unique()
log_mod = sm.Logit(df_new['converted'], df_new[['intercept', 'CA', 'US']])
results = log_mod.fit()
results.summary()
print(np.exp(res.params))
Congratulations on completing the project!
Once you are satisfied with the status of your Notebook, you should save it in a format that will make it easy for others to read. You can use the File -> Download as -> HTML (.html) menu to save your notebook as an .html file. If you are working locally and get an error about "No module name", then open a terminal and try installing the missing module using pip install <module_name>
(don't include the "<" or ">" or any words following a period in the module name).
You will submit both your original Notebook and an HTML or PDF copy of the Notebook for review. There is no need for you to include any data files with your submission. If you made reference to other websites, books, and other resources to help you in solving tasks in the project, make sure that you document them. It is recommended that you either add a "Resources" section in a Markdown cell at the end of the Notebook report, or you can include a readme.txt
file documenting your sources.
When you're ready, click on the "Submit Project" button to go to the project submission page. You can submit your files as a .zip archive or you can link to a GitHub repository containing your project files. If you go with GitHub, note that your submission will be a snapshot of the linked repository at time of submission. It is recommended that you keep each project in a separate repository to avoid any potential confusion: if a reviewer gets multiple folders representing multiple projects, there might be confusion regarding what project is to be evaluated.
It can take us up to a week to grade the project, but in most cases it is much faster. You will get an email once your submission has been reviewed. If you are having any problems submitting your project or wish to check on the status of your submission, please email us at dataanalyst-project@udacity.com. In the meantime, you should feel free to continue on with your learning journey by beginning the next module in the program.